﻿namespace SendingEmail
{
    using System;
    using System.Net;
    using System.Net.Mail;

    /// <summary>
    /// This example demonstrates sending mail using Gmail. You can use these configurations
    /// to send email with Yahoo, Gmail, and Hotmail.
    /// --------------------------------------------------
    /// | Server Name | SMTP Address        | Port | SSL |
    /// --------------------------------------------------
    /// | Yahoo       | smtp.mail.yahoo.com | 587  | Yes |
    /// | GMail       | smtp.gmail.com      | 587  | Yes |
    /// | Hotmail     | smtp.live.com       | 587  | Yes |
    /// --------------------------------------------------
    /// </summary>
    public class SendingEmailTask
    {
        public SendingEmailTask() { }

        public void SendEmail()
        {
            // These configurations should be stored in database
            const string SmtpAddress = "smtp.gmail.com";
            const int PortNumber = 587;
            const bool EnableSSL = true;

            // The mail content is retrieved from database
            string senderAddress = "SenderAddress@gmail.com";
            string senderPassword = "SenderPassword";
            string receiverAddress = "ReceiverAddress";
            string subject = "Testing Sending Gmail";
            string body = "Dear Receiver<br><br>This message is from Sending Email Task.<br><br>Kind Regards<br><b>Sending Email Task</b>";

            try
            {
                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(senderAddress);
                    mail.To.Add(receiverAddress);
                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = true;

                    //mail.Attachments.Add(new Attachment(@"C:\Projects\LearningProgramming\SendingEmail\Attachments\Attachment01.txt"));
                    //mail.Attachments.Add(new Attachment(@"C:\Projects\LearningProgramming\SendingEmail\Attachments\Attachment02.zip"));

                    using (SmtpClient smtp = new SmtpClient(SmtpAddress, PortNumber))
                    {
                        smtp.Credentials = new NetworkCredential(senderAddress, senderPassword);
                        smtp.EnableSsl = EnableSSL;
                        smtp.Send(mail);
                    }
                }
            }
            catch (Exception ex)
            {
                // Log error message.
                System.Console.WriteLine(string.Format("Failed to send email: {0}", ex.Message));
            }
        }
    }
}
